<template>
  <div>
    <div class="listManager-btnGroup-wrap">
      <div class="listManager-btnGroup-left">
        <el-form inline :model="searchForm" ref="searchForm" :label-width="formLabelWidth">
          <el-form-item label="数据范围"
                        prop="range">
            <el-select style="width: 100%" v-model="searchForm.range">
              <el-option v-for="item in dataRangeArr" :key="item.id" :label="item.pName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="名称"
                        prop="label">
            <el-input v-model="searchForm.label" placeholder="请输入名称"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="search">搜索</el-button>
            <el-button icon="el-icon-refresh-left" @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>

      </div>
      <div class="listManager-btnGroup">
        <el-button icon="el-icon-circle-plus-outline" type="primary" @click="addDepartment('添加','add', null)">添加
        </el-button>
      </div>
    </div>
    <table-encapsulation row-key="id" :loading="loadingBtn.treeLoading" :columnData="columnData"
                         :tableSize="pagination.pageSize"
                         :tableData="tableData" :tableTotal="pagination.total"
                         @currentPage="handleCurrentChange">

      <el-table-column align="center" slot="operate"
                       label="操作" width="200">
        <template slot-scope="scope">
          <el-tooltip v-if="scope.row.pId==='0'" class="item" effect="dark" content="添加"
                      placement="top">
            <i class="el-icon-circle-plus-outline table-icon-btn color-primary"
               @click="addDepartment('添加','add', scope.row)"></i>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="编辑" placement="top">
            <i class="el-icon-edit-outline table-icon-btn color-primary"
               @click="addDepartment('编辑','edit', scope.row)"></i>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top">
            <i class="el-icon-delete table-icon-btn color-error" @click="delDepartment(scope.row)"></i>
          </el-tooltip>
        </template>
      </el-table-column>
    </table-encapsulation>
    <el-dialog :title="dialog.title" :visible.sync="dialogVisible" @closed="closeDialog">
      <el-form v-loading="loadingBtn.diaSubmitBtn" :model="departmentForm" ref="departmentForm"
               :label-width="formLabelWidth"
               :rules="departmentFormRule">
        <el-form-item label="名称" prop="label">
          <el-input v-model="departmentForm.label"></el-input>
        </el-form-item>
        <el-form-item label="标识"
                      prop="code">
          <el-input v-model="departmentForm.code"></el-input>
        </el-form-item>
        <el-form-item label="数据范围"
                      prop="range">
          <el-select style="width: 100%" v-model="departmentForm.range">
            <el-option v-for="item in dataRangeArr" :key="item.id" :label="item.pName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :loading="loadingBtn.diaSubmitBtn" type="primary" @click="departmentFormSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { validUppercaseLetter } from '@/common/validate/formValidate'
import { insert, listDepartmentLimit, update, deleteDepartment } from '@/api/system/department'
import { listDicByParentCode } from '@/api/system/dictionary'
import tableEncapsulation from '@/components/tableEncapsulation'

export default {
  components: {
    tableEncapsulation
  },
  data () {
    return {
      // 分页数据
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        params: {}
      },
      // 加载状态
      loadingBtn: {
        diaSubmitBtn: false,
        treeLoading: false
      },
      // table 数据
      tableData: [],
      // 弹出窗 数据
      dialog: {
        title: '',
        flag: ''
      },
      // 弹出窗 显隐状态
      dialogVisible: false,
      // 数据范围下拉
      dataRangeArr: [],
      // form 表单数据
      departmentForm: {
        range: null,
        label: null,
        code: null
      },
      // 搜索 表单数据
      searchForm: {
        range: null,
        label: null
      },
      columnData: [
        {
          type: 'index',
          label: '序号'
        }, {
          label: '名称',
          prop: 'label'
        }, {
          label: '标识',
          prop: 'code'
        }, {
          label: '数据范围',
          prop: 'dicName'
        }, {
          slot: 'operate',
          label: '操作'
        }
      ],
      // 表单校验规则
      departmentFormRule: {
        label: [
          { required: true, message: '请填写名称', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请填写标识', trigger: 'blur' },
          { validator: validUppercaseLetter, trigger: 'blur' }
        ],
        range: [
          { required: true, message: '请选择数据范围', trigger: 'change' }
        ]
      },
      // 表单标签宽度
      formLabelWidth: '100px'
    }
  },
  methods: {
    previewFile (file) {
      if (file.status === 'success') {
        window.open(file.url)
      }
    },
    /**
     * 分页点击事件
     */
    handleCurrentChange (currentPage) {
      this.pagination.pageNum = currentPage
      this.getTableData()
    },
    /**
     * 删除单条操作
     */
    delDepartmentAction (row) {
      deleteDepartment(row.id).then(res => {
        const code = res.code
        const msg = res.msg
        if (code === this.$constant.SUCCESS) {
          this.$message.success(msg)
          this.getTableData()
        }
      })
    },
    /**
     * 删除按钮点击事件
     */
    delDepartment (row) {
      this.$confirm('是否确认删除?', '确认删除').then(_ => {
        this.delDepartmentAction(row)
      }).catch(_ => {
      })
    },
    /**
     * 添加或编辑的点击事件按钮点击事件
     */
    addDepartment (title, flag, data) {
      this.dialog.title = title
      this.dialog.flag = flag
      this.dialogVisible = true
      switch (flag) {
        case 'edit':
          this.departmentForm = data
          break
        case 'add':
          if (data) {
            this.departmentForm.pId = data.id
          }
          break
      }
    },
    /**
     * 添加或编辑的提交操作
     */
    departmentFormSubmit () {
      this.$refs.departmentForm.validate((valid) => {
        if (valid) {
          this.loadingBtn.diaSubmitBtn = true
          if (this.dialog.flag === 'add') {
            insert(this.departmentForm).then(({ msg, code }) => {
              if (code === this.$constant.SUCCESS) {
                this.$message.success(msg)
                this.dialogVisible = false
                this.getTableData()
              }
              this.loadingBtn.diaSubmitBtn = false
            })
          } else if (this.dialog.flag === 'edit') {
            update(this.departmentForm).then(({ msg, code }) => {
              if (code === this.$constant.SUCCESS) {
                this.$message.success(msg)
                this.dialogVisible = false
                this.getTableData()
              }
              this.loadingBtn.diaSubmitBtn = false
            })
          }
        }
      })
    },
    /**
     * 重置按钮
     */
    resetSearch () {
      this.$refs.searchForm.resetFields()
      this.pagination.pageNum = 1
      this.pagination.params.range = null
      this.pagination.params.label = null
      this.getTableData()
    },
    /**
     * 搜索按钮
     */
    search () {
      this.pagination.params.range = this.searchForm.range
      this.pagination.params.label = this.searchForm.label
      this.pagination.pageNum = 1
      this.getTableData()
    },
    /**
     * 关闭分配角色弹窗
     */
    closeDialog () {
      this.departmentForm = {
        range: null,
        label: null,
        code: null
      }
      this.loadingBtn.diaSubmitBtn = false
      this.dialog.flag = ''
      this.dialog.title = ''
      this.$nextTick(() => {
        this.$refs.departmentForm.clearValidate()
      })
    },
    /**
     * 获取table数据
     */
    getTableData () {
      this.loadingBtn.treeLoading = true
      listDepartmentLimit(this.pagination).then(({ data, code }) => {
        if (code === this.$constant.SUCCESS) {
          this.tableData = data.list
          this.pagination.total = data.total
        }
        this.loadingBtn.treeLoading = false
      }).catch(_ => {
        this.loadingBtn.treeLoading = false
      })
    },
    getDataRange () {
      listDicByParentCode('BMSJFW').then(({ data, code }) => {
        if (code === this.$constant.SUCCESS) {
          this.dataRangeArr = data
        }
      })
    }
  },
  created () {
    this.getDataRange()
    this.getTableData()
  }
}
</script>

<style scoped>
.custom-tree-node {
  width: 100%;
  position: relative;
}

.operate-btns {
  position: absolute;
  top: 0;
  right: 0;
}
</style>
